/*FILE UPDATE INFO**************************************************************
 * Author   : PURESUN
 * Update   : 2024-03-23
 * Info     : serial port communication library
 * Version  : 1.0.0
 ******************************************************************************/

/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __SERIAL_H__
#define __SERIAL_H__

/* Includes ------------------------------------------------------------------*/
#include "puresun_type.h"
#include "pthread.h"
#include "termios.h"

/* Exported macro ------------------------------------------------------------*/
#define DEFAULT_BAUD 9600

/* Exported typedef ----------------------------------------------------------*/
typedef void (*serial_rcv_handler_t)(byte *data, int len);

typedef enum _serial_parity_t
{
    SERIAL_PARITY_NONE = 0,
    SERIAL_PARITY_ODD = PARODD,
    SERIAL_PARITY_EVEN = PARENB
} serial_parity_t;

typedef enum _serial_flow_control_t
{
    SERIAL_FLOW_CONTROL_NONE = 0,
    SERIAL_FLOW_CONTROL_HARDWARE,
    SERIAL_FLOW_CONTROL_SOFTWARE
} serial_flow_control_t;

typedef enum _serial_data_bits_t
{
    SERIAL_DATA_BITS_5 = CS5,
    SERIAL_DATA_BITS_6 = CS6,
    SERIAL_DATA_BITS_7 = CS7,
    SERIAL_DATA_BITS_8 = CS8
} serial_data_bits_t;

typedef enum _serial_stop_bits_t
{
    SERIAL_STOP_BITS_1 = 0,
    SERIAL_STOP_BITS_2 = CSTOPB
} serial_stop_bits_t;

typedef struct _serial_config_t
{
    int baud;
    string port; // /dev/ttyS1, /dev/ttyS2
    serial_parity_t parity;
    serial_flow_control_t flow_control;
    serial_data_bits_t data_bits;
    serial_stop_bits_t stop_bits;
    int read_timeout;  // unit: ms
    int rxbuffer_size; // unit: byte
} serial_config_t;

typedef struct _serial_t
{
    int fd; // file descriptor
    // byte *rxbuffer; // receive buffer
    // int rxlen;      // receive buffer length
    pthread_mutex_t mutex;
    serial_rcv_handler_t rxhandler;
    serial_config_t config;
    pthread_t thread;
} serial_t;

/* Exported types ------------------------------------------------------------*/

/* Exported constants --------------------------------------------------------*/

/* Exported variables --------------------------------------------------------*/

/* Exported functions --------------------------------------------------------*/
void serial_init(serial_t *serial, serial_config_t *config);
void serial_open(serial_t *serial);
void serial_close(serial_t *serial);
int serial_write(serial_t *serial, byte *data, int len);
void serial_receive_handler_register(serial_t *serial, serial_rcv_handler_t handler);
uint32_t sys_run_ms(void);

#endif /* __VAACUM_H__ */

/************************ (C) COPYRIGHT PURESUN *****END OF FILE***************/
